<?php
/**
 * Created by Yevgen Vershynin.
 * User: Yevgen Vershynin
 * Description: Model for Employee entity. Implements creation, deleting and fetching Employee data from DB.
 */
class EmployeeModel
{
    public function getEmployeeById($emplId)
    {
        $db = DbComponent::getInstance();
        $rawData = $db->queryRow("SELECT * FROM employees WHERE employeeNumber = ".$emplId);

        if(!empty($rawData))
        {
            $employee = new EmployeeObject($rawData);
        }
        else
        {
            $employee = array("error"=>"Wrong employee number code.");
        }

        return $employee;
    }

    public function getAllEmployees()
    {
        $db = DbComponent::getInstance();
        $rawData = $db->queryAll("SELECT * FROM employees");

        if(!empty($rawData))
        {
            foreach($rawData as $emplData)
            {
                $employees[] = new EmployeeObject($emplData);
            }
        }
        else
        {
            $employees = array("error"=>"There is no employees");
        }

        return $employees;
    }

    public function createEmployee($emplData)
    {
        $employee = new EmployeeObject($emplData);
        $db = DbComponent::getInstance();
        $affectedRows = $db->insert(
            "INSERT INTO employees(employeeNumber, lastName, firstName, extension, email, officeCode, reportsTo,
            jobTitle)
            select (MAX(employeeNumber)+1), '$employee->lastName','$employee->firstName','$employee->extension'
            ,'$employee->email','$employee->officeCode','$employee->reportsTo','$employee->jobTitle'
            FROM employees
        ");

        return ($affectedRows > 0);
    }

    public function updateEmployee($emplData)
    {
        $employee = new EmployeeObject($emplData);
        if(!empty($employee->employeeNumber))
        {
            $db = DbComponent::getInstance();
            $affectedRows = $db->insert(
                "UPDATE employees set lastName='$employee->lastName', firstName='$employee->firstName',
                extension='$employee->extension', email='$employee->email', officeCode='$employee->officeCode',
                reportsTo='$employee->reportsTo', jobTitle='$employee->jobTitle'
                WHERE employeeNumber = $employee->employeeNumber
            ");

            return ($affectedRows > 0);
        }
        else
        {
            return false;
        }
    }

    public function deleteEmployee($emplId)
    {
        $db = DbComponent::getInstance();
        $affectedRows = $db->insert("DELETE FROM employees WHERE employeeNumber=".$emplId);
        return ($affectedRows > 0);
    }
}
